
import json
import os
import uuid
from utils.randomUtils import generate_random_from_username_password

class UserDBManager:
    def __init__(self, users_db='./db/data/users_data.json'):
        self.users = {}
        self.users_db = users_db
        with open(users_db, 'r') as f:
            self.users = json.load(f)    

    
    def register(self, username, user_email, user_password)-> bool:
        user_id = generate_random_from_username_password(username, user_password)
        if user_id in self.users:
            return None
        self.users[user_id] = {
            'username': username,
            'user_email': user_email,
            'user_password': user_password,
            'user_projects': {}
        }
        try:
            with open(f'./db/data/users/{user_id}.json', 'w') as f:
                json.dump({}, f)
            with open(self.users_db, 'w') as f:
                json.dump(self.users, f)
            # ToDO
            # 连接到sqlite
            # 连接到UserDB表（用来存User的登陆和其他的信息（密码、头像的URL、team等）
            # 增加一个用户
            # 连接到UserProjects表啥也不干
        except Exception as e:
            print(e)
            return None
        return user_id
    
    def login(self, username, password):
        for user_id, user in self.users.items():
            if user['username'] == username and user['user_password'] == password:
                return user_id
        return None

    def get_user_login_info(self, user_id):
        return self.users.get(user_id, None)
    
    def get_user_projects(self, user_id):
        projects = {}
        with open(f'./db/data/users/{user_id}.json', 'r') as f:
            projects = json.load(f)
        # ToDO
        # 连接到UserProjects表（用来存User的所有项目数据）  
        # 读一下userid的行的第二个（projects）
        return projects

    def save_user_projects(self, user_id, projects):
        with open(f'./db/data/users/{user_id}.json', 'w') as f:
            json.dump(projects, f)
        # ToDO
        # 连接到UserProjects表（用来存User的所有项目数据）
        # 写入一条userid，projects
        return True
    def update_user_info(self, user_id, new_info):
        if user_id not in self.users:
            return False
        self.users[user_id].update(new_info)
        with open(self.users_db, 'w') as f:
            json.dump(self.users, f, indent=4, ensure_ascii=False)
        return True

    def delete_account(self, user_id):
        try:
            # 1. 检查用户是否存在
            if user_id not in self.users:
                return False
            # 2. 删除用户个人数据文件
            user_file = f'./db/data/users/{user_id}.json'
            print(f"尝试删除的文件路径: {os.path.abspath(f'./db/data/users/{user_id}.json')}")
            if os.path.exists(user_file):
                os.remove(user_file)

            # 3. 从主用户数据库中删除用户
            del self.users[user_id]
            # 4. 保存更新后的用户数据库
            with open(self.users_db, 'w') as f:
                json.dump(self.users, f)
            return True

        except Exception as e:
            print(f"Error deleting account: {e}")
            return False


